package timbap.artwork.gui;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import timbap.artwork.retrieval.ArtworkRetriever;
import timbap.artwork.retrieval.YahooArtworkRetrieverImpl;
import timbap.visualizer.api.context.Configuration;
import timbap.visualizer.api.context.playlist.PlaylistManager;
import timbap.visualizer.api.exceptions.NoPlaylistSelectedException;
import timbap.visualizer.api.exceptions.PlaylistParserException;
import timbap.visualizer.api.model.PlaylistEntry;
import timbap.visualizer.impl.context.playlist.ExtM3UPlaylistManagerImpl;
import timbap.visualizer.impl.context.playlist.ITunesLibraryParsingPopupPlaylistChooserImpl;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import java.awt.Color;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;

public class ArtworkFinderApp {

    private static final Log LOG = LogFactory.getLog(ArtworkFinderApp.class);

    JFrame appFrame;
    PlaylistManager playlistManager;
    Configuration cfg;

    public ArtworkFinderApp() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception e) {
            e.printStackTrace();
        }
        cfg = initCfg();
        initPlaylistManager();
        initFrame();
    }

    private Configuration initCfg() {
        Configuration tCfg = new Configuration();
        tCfg.load();
        return tCfg;
    }

    private void initPlaylistManager() {

        playlistManager = new ExtM3UPlaylistManagerImpl();
        playlistManager.setPlaylistChooser(new ITunesLibraryParsingPopupPlaylistChooserImpl(cfg));

        File[] tPlaylistFiles = null;
        File tPlaylistDirectory = cfg.getDefaultPlaylistDirectory();
        if (tPlaylistDirectory.canRead()) {
            tPlaylistFiles = tPlaylistDirectory.listFiles(new FileFilter() {
                public boolean accept(File pathname) {
                    return pathname.getName().endsWith(".m3u");
                }
            }
            );
        }
        if (tPlaylistFiles == null || tPlaylistFiles.length == 0) {
            LOG.error("No playlists found in directory " + tPlaylistDirectory.getAbsolutePath() + ". Quitting ...");
            System.exit(0);
        }

        LOG.info("Initializing playlist manager ...");

        try {
            playlistManager.init(cfg);
        } catch (NoPlaylistSelectedException e) {
            LOG.error(e,e);
            System.exit(0);
        } catch (PlaylistParserException e) {
            LOG.error(e,e);
        }

        Collections.sort(playlistManager.getPlaylist(), new Comparator<PlaylistEntry>() {
            public int compare(final PlaylistEntry o1, final PlaylistEntry o2) {
                String tArtistName1 = o1.getArtistName();
                String tArtistName2 = o2.getArtistName();
                if (tArtistName1 == null) {
                    return 1;
                } else {
                    int tResult = tArtistName1.compareTo(tArtistName2);
                    if (tResult != 0) {
                        return tResult;
                    } else {
                        String tSongTitle1 = o1.getSongTitle();
                        String tSongTitle2 = o2.getSongTitle();
                        if (tSongTitle1 == null) {
                            return 1;
                        } else {
                            return tSongTitle1.compareTo(tSongTitle2);
                        }
                    }
                }
            }
        });
    }

    private void initFrame() {
        Image tDefaultArtworkImage = null;
        try {
            tDefaultArtworkImage = ImageIO.read(
                    cfg.getDefaultArtworkFile()).getScaledInstance(-1, 100, Image.SCALE_SMOOTH);
        } catch (IOException e) {
            e.printStackTrace();
        }

        ArtworkRetriever tArtworkRetriever = new YahooArtworkRetrieverImpl();

        appFrame = new JFrame("Artwork Finder for timbap");
        appFrame.setSize(1100, 600);
        Container tMainPanel = new JPanel();
        tMainPanel.setLayout(new GridBagLayout());
        tMainPanel.setBackground(new Color(50,0,0));
        int tRowNumber = 0;

        for (PlaylistEntry tPlaylistEntry : playlistManager.getPlaylist()) {
            PlaylistEntryControlPanel tPlaylistEntryControlPanel =
                    new PlaylistEntryControlPanel(tPlaylistEntry, tDefaultArtworkImage, tArtworkRetriever);
            GridBagConstraints tGridBagConstraints = new GridBagConstraints();
            tGridBagConstraints.gridy = tRowNumber;
            tGridBagConstraints.insets = new Insets(10,0,0,0);
            tGridBagConstraints.fill = GridBagConstraints.HORIZONTAL;
            tMainPanel.add(tPlaylistEntryControlPanel.getComponent(), tGridBagConstraints);
            tRowNumber++;
        }

        JScrollPane tScrollPane = new JScrollPane(tMainPanel);
        appFrame.getContentPane().add(tScrollPane);
        appFrame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(final WindowEvent e) {
                System.exit(0);
            }
        });
        appFrame.setVisible(true);
    }


    public static void main(String[] args) {
        new ArtworkFinderApp();
    }

}
